//
//  DiscoverExploreViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/6/17.
//

#import "DiscoverExploreViewController.h"
#import "DiscoverExploreListCell.h"
#import "DiscoverExploreManager.h"
#import "DiscoverExploreListModel.h"
#import "DiscoverExploreDetialViewController.h"
#import "LoginViewController.h"

@interface DiscoverExploreViewController()<UITableViewDelegate,UITableViewDataSource,JPAPIManagerCallBackDelegate>

@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)DiscoverExploreManager *exploreManager;
@property(nonatomic,strong)NSMutableArray *dataArr;
@property(nonatomic,assign)NSInteger page;

@end

@implementation DiscoverExploreViewController

-(DiscoverExploreManager *)exploreManager{
    if(!_exploreManager){
        _exploreManager = [[DiscoverExploreManager alloc]init];
        _exploreManager.delegate = self;
    }
    return _exploreManager;
}

-(NSMutableArray *)dataArr{
    if(!_dataArr){
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

-(void)viewDidLoad{
    [super viewDidLoad];
    
    self.page = 1;
    [self createUI];
    [self loadListData];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loginSuccess:) name:@"loginSuccess" object:nil];
        
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(logoutSuccess) name:@"logoutSuccess" object:nil];
    
}

#pragma mark - 登录成功
-(void)loginSuccess:(NSNotification*)notifi{
    if(self.dataArr.count == 0){
        self.page = 1;
        [self loadListData];
    }
}

#pragma mark - 退出登录成功
-(void)logoutSuccess{
    if(self.dataArr.count == 0){
        self.page = 1;
        [self loadListData];
    }
}

#pragma mark - 获取列表数据
-(void)loadListData{
    self.exploreManager.page = [NSString stringWithFormat:@"%ld",self.page];
    [self.exploreManager loadData];
}

-(void)createUI{
    
    self.customNavigationBar.hidden = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-kYM_TABBAR_HEIGHT) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:NSClassFromString(@"DiscoverExploreListCell") forCellReuseIdentifier:@"DiscoverExploreListCell"];
    self.tableView.rowHeight = 100;
    [self.view addSubview:self.tableView];
    
    __weak typeof(self)self_weak_ = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self_weak_.dataArr removeAllObjects];
        self_weak_.page = 1;
        [self_weak_ loadListData];
    }];
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        self_weak_.page++;
        [self_weak_ loadListData];
    }];
    
}

#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    if(isIPAD){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            // 获取当前可用宽度并更新布局
            self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
            self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
            self.customNavigationBar.frame = CGRectMake(0,0,self.currentAvailableWidth,kYM_NAVIGATIONBAR_HEIGHT);
            self.tableView.frame = CGRectMake(0, 0, self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT-kYM_TABBAR_HEIGHT);
            [self.tableView reloadData];
            
        });
    }
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DiscoverExploreListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DiscoverExploreListCell"];
    if(indexPath.row < self.dataArr.count){
        DiscoverExploreListModel *model = self.dataArr[indexPath.row];
        cell.model = model;
    }
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    if(userId){
//        NSString *loginMode = [[NSUserDefaults standardUserDefaults]objectForKey:@"loginMode"];
//        if(loginMode&&[loginMode isEqualToString:@"4"]){
//            //游客需要登录
//            [self login];
//        }else{
            DiscoverExploreListCell *selectedCell = (DiscoverExploreListCell*) [tableView cellForRowAtIndexPath:indexPath];
            if(indexPath.row < self.dataArr.count){
                DiscoverExploreListModel *model = self.dataArr[indexPath.row];
                DiscoverExploreDetialViewController *vc = [[DiscoverExploreDetialViewController alloc]init];
                vc.shareImage = selectedCell.articleImageView.image;
                vc.exploreListModel = model;
                [self.navigationController pushViewController:vc animated:YES];
            }
//        }
    }else{
        [self login];
    }
}

#pragma mark - 登录
-(void)login{
    LoginViewController *vc = [[LoginViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - JPAPIManagerCallBackDelegate
-(void)managerCallDLDLAPIDidSuccess:(JPAPIBaseManager *)manager{
    
    if([manager isEqual:self.exploreManager]){
        NSDictionary *dic = manager.response.content;
        NSArray *arr = [DiscoverExploreListModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
        self.dataArr = [NSMutableArray arrayWithArray:arr];
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }
    
}

-(void)managerCallDLDLAPIDidFailed:(JPAPIBaseManager *)manager{
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
    if(manager.errorMessage){
        [JPProgressHUD showMsg:manager.errorMessage];
    }
}


@end
